/**	
 * Author : Mht
 * Desc : For 2016 RDM 
 */
package dynamic;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.Validate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;

/**
 * @author Mht
 * @date Jun 14, 2016
 */
public class RoutingTransactionManager implements PlatformTransactionManager {

	private Map<Object, PlatformTransactionManager> targetTransactionManagers = new HashMap<Object, PlatformTransactionManager>();

	/**
	 * 根据给定的规则获取指定的tx
	 * 
	 * @return
	 */
	protected PlatformTransactionManager getTargetTransactionManager() {
		Object context = RoutingContextHolder.getContext();
		Validate.notNull(context, "Must have context!");
		return targetTransactionManagers.get(context);
	}

	public void setTargetTransactionManagers(Map<Object, PlatformTransactionManager> targetTransactionManagers) {
		this.targetTransactionManagers = targetTransactionManagers;
	}

	public void commit(TransactionStatus status) throws TransactionException {
		getTargetTransactionManager().commit(status);
	}

	public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
		return getTargetTransactionManager().getTransaction(definition);
	}

	public void rollback(TransactionStatus status) throws TransactionException {
		getTargetTransactionManager().rollback(status);
	}
}
